

function getDomain(url)
{
	var matchArr = url.match(/:\/\/(www\.)?(.[^/:]+)/);
	return matchArr && matchArr[2];
}

chrome.extension.sendMessage({message: "website_data"}, function(response) {
	var specialUrls = ['http://www.facebook.com/l.php?u='];

    var websites = response.websites;
	
	var longUrlApi = 'http://longurlplease.appspot.com/api/v1.1?';
	var longUrlApiLength = longUrlApi.length;
	
	var links = document.getElementsByTagName('a');
	var encodedLinks = [];
	var encodedLinksRequest = longUrlApi;
	
	for (var i = 0; i < links.length; i++) {
		var link = links[i];
		
		// add special checks
		for (var j = 0; j < specialUrls.length; j++) {
			if (link.href.indexOf(specialUrls[j]) == 0) {
				var newUrl = decodeURIComponent(link.href.replace(specialUrls[j], ""));
				var ampIndex = newUrl.indexOf('&');
				if (ampIndex != -1) {
					newUrl = newUrl.substring(0, ampIndex);
				}
				if (link.innerText === link.href) {
					link.innerText = newUrl;
				}
				link.href = newUrl;
				break;
			}
		}
		
		var linkDomain = getDomain(link.href);
		if (!linkDomain) {
			continue;
		}
		
		var index = websites.indexOf(getDomain(link.href));		
		if (index != -1) {
			encodedLinks.push(link);
		
			if (encodedLinksRequest.length !== longUrlApiLength) {
				encodedLinksRequest += '&';
			}
			
			encodedLinksRequest += 'q=' + link.href;
		}
	}
	
	if (encodedLinksRequest.length !== longUrlApiLength) {
		chrome.extension.sendMessage({
			message: "getLongifiedUrls",
			encodedLinksRequest: encodedLinksRequest
		}), function(response) {
			console.log(response);
		}
	}
});

